﻿using Basic.Repository.Abstract.Entities;
using Newtonsoft.Json;

namespace System;

public static class PropertiesExtension
{
    /// <summary>
    /// 读取[IExtensionProperties]属性
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="properties"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static T GetProperty<T>(this IExtensionProperties properties, string key)
    {
        if (!string.IsNullOrEmpty(properties.ExtensionJson))
        {
            var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(properties.ExtensionJson);
            if (dict.TryGetValue(key, out string valStr) && !string.IsNullOrEmpty(valStr))
                return JsonConvert.DeserializeObject<T>(valStr);
        }
        return default(T);
    }

    /// <summary>
    /// 设置[IExtensionProperties]属性
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="properties"></param>
    /// <param name="key"></param>
    /// <param name="obj"></param>
    public static void SetProperty<T>(this IExtensionProperties properties, string key, T obj)
    {
        var dict = string.IsNullOrEmpty(properties.ExtensionJson) ? (new Dictionary<string, string>()) : JsonConvert.DeserializeObject<Dictionary<string, string>>(properties.ExtensionJson);
        dict[key] = JsonConvert.SerializeObject(obj);
        properties.ExtensionJson = JsonConvert.SerializeObject(dict);
    }

}